<template>
  <div class="create-mutual">
    <el-card class="form-card" v-loading="loading">
      <!-- 步骤条 -->
      <div class="step-header">
        <h2 class="page-title">
          <i class="el-icon-edit-outline"></i>
          发起合作
        </h2>
        <el-steps 
          :active="activeStep" 
          finish-status="success" 
          align-center 
          class="custom-steps"
        >
          <el-step title="基本信息" icon="el-icon-document"></el-step>
          <el-step title="参与设置" icon="el-icon-setting"></el-step>
          <el-step title="通知设置" icon="el-icon-bell"></el-step>
          <el-step title="优先推送" icon="el-icon-user"></el-step>
        </el-steps>
      </div>

      <el-form 
        :model="formData" 
        :rules="rules"
        ref="mutualForm"
        label-width="100px"
        size="small"
      >
        <!-- 步骤1：基本信息 -->
        <div v-show="activeStep === 0" class="step-content" :class="{'is-active': activeStep === 0}">
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-document"></i>
              <span>基本信息</span>
            </div>
            <el-form-item label="需求类别" prop="demandCategory">
              <el-select 
                v-model="formData.demandCategory" 
                placeholder="请选择需求类别"
                style="width: 100%"
              >
                <el-option 
                  v-for="item in demandCategories" 
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <i class="el-icon-collection-tag"></i>
                  <span>{{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="标题" prop="title">
              <el-input 
                v-model="formData.title" 
                placeholder="请输入标题"
                prefix-icon="el-icon-edit"
                style="width: 100%"
              ></el-input>
            </el-form-item>

            <el-form-item label="详细描述" prop="description">
              <el-input 
                type="textarea" 
                v-model="formData.description" 
                :rows="4"
                placeholder="请输入详细描述"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </div>
        </div>

        <!-- 步骤2：参与设置 -->
        <div v-show="activeStep === 1" class="step-content" :class="{'is-active': activeStep === 1}">
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-setting"></i>
              <span>参与设置</span>
            </div>
            <el-form-item label="需要报名">
              <el-switch
                v-model="formData.needRegistration"
                active-color="#409EFF"
                inactive-color="#dcdfe6"
              >
              </el-switch>
              <span class="switch-tip">{{ formData.needRegistration ? '需要报名' : '无需报名' }}</span>
            </el-form-item>

            <el-form-item label="有效期至" prop="effectiveDate">
              <el-date-picker
                v-model="formData.effectiveDate"
                type="date"
                placeholder="选择有效期"
                value-format="yyyy-MM-dd"
                style="width: 100%"
                :picker-options="{
                  disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7;
                  }
                }"
              ></el-date-picker>
            </el-form-item>
          </div>
        </div>

        <!-- 步骤3：通知设置 -->
        <div v-show="activeStep === 2" class="step-content" :class="{'is-active': activeStep === 2}">
          <div class="form-section">
            <div class="section-title">通知设置</div>
            <el-form-item label="开启通知">
              <el-switch
                v-model="formData.notificationEnabled"
                active-color="#409EFF"
              ></el-switch>
            </el-form-item>

            <template v-if="formData.notificationEnabled">
              <el-form-item label="通知截止时间" prop="notificationDeadline">
                <el-date-picker
                  v-model="formData.notificationDeadline"
                  type="datetime"
                  placeholder="选择通知截止时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 80%"
                ></el-date-picker>
              </el-form-item>

              <el-form-item label="通知内容" prop="notificationContent">
                <el-input 
                  type="textarea"
                  v-model="formData.notificationContent"
                  :rows="4"
                  placeholder="请输入通知内容"
                  style="width: 80%"
                ></el-input>
              </el-form-item>
            </template>
          </div>
        </div>

        <!-- 步骤4：优先推送人群 -->
        <div v-show="activeStep === 3" class="step-content" :class="{'is-active': activeStep === 3}">
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-user"></i>
              优先推送人群
            </div>
            
            <el-form-item label="专长领域" prop="priorityField">
              <el-cascader
                v-model="formData.priorityField"
                :options="fieldOptions"
                :props="{
                  multiple: true,
                  checkStrictly: true,
                  value: 'dictName',
                  label: 'dictName',
                  children: 'children',
                  lazy: true,
                  lazyLoad: handleFieldLazyLoad,
                  emitPath: false
                }"
                clearable
                collapse-tags
                placeholder="请选择专长领域"
                @change="handleFieldChange"
              ></el-cascader>
            </el-form-item>

            <el-form-item label="工作方向" prop="priorityDirection">
              <el-cascader
                v-model="formData.priorityDirection"
                :options="directionOptions"
                :props="{
                  multiple: true,
                  checkStrictly: true,
                  value: 'dictName',
                  label: 'dictName',
                  children: 'children',
                  lazy: true,
                  lazyLoad: handleDirectionLazyLoad,
                  emitPath: false
                }"
                clearable
                collapse-tags
                placeholder="请选择工作方向"
                @change="handleDirectionChange"
              ></el-cascader>
            </el-form-item>

            <el-form-item label="兴趣爱好" prop="priorityHobbies">
              <el-cascader
                v-model="formData.priorityHobbies"
                :options="hobbiesOptions"
                :props="{
                  multiple: true,
                  checkStrictly: true,
                  value: 'dictName',
                  label: 'dictName',
                  children: 'children',
                  lazy: true,
                  lazyLoad: handleHobbiesLazyLoad,
                  emitPath: false
                }"
                clearable
                collapse-tags
                placeholder="请选择兴趣爱好"
                @change="handleHobbiesChange"
              ></el-cascader>
            </el-form-item>
          </div>
        </div>

        <!-- 步骤操作按钮 -->
        <div class="step-actions">
          <el-button 
            @click="prevStep" 
            v-if="activeStep > 0"
            :disabled="loading"
            icon="el-icon-arrow-left"
          >上一步</el-button>
          <el-button 
            type="primary" 
            @click="activeStep === 3 ? submitForm() : nextStep()"
            :disabled="loading"
            :icon="activeStep === 3 ? 'el-icon-check' : 'el-icon-arrow-right'"
          >
            {{ activeStep === 3 ? '提交' : '下一步' }}
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { createMutual, getDictValue } from "@/api/api";

export default {
  name: 'CreateMutual',
  data() {
    return {
      activeStep: 0,
      loading: false,
      isInitialized: false,
      demandCategories: [
        { label: '租房借房', value: '租房借房' },
        { label: '招聘求职', value: '招聘求职' },
        { label: '子女就学', value: '子女就学' },
        { label: '求医问药', value: '求医问药' },
        { label: '商业（资源）对接', value: '商业（资源）对接' },
        { label: '闲置交易', value: '闲置交易' }
      ],
      formData: {
        demandCategory: '',
        title: '',
        description: '',
        priorityField: [],
        priorityDirection: [],
        priorityHobbies: [],
        needRegistration: false,
        effectiveDate: '',
        notificationEnabled: false,
        notificationDeadline: '',
        notificationContent: ''
      },
      rules: {
        demandCategory: [
          { required: true, message: '请选择需求类别', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入详细描述', trigger: 'blur' }
        ],
        effectiveDate: [
          { required: true, message: '请选择有效期', trigger: 'change' }
        ],
        priorityField: [{ type: 'array', required: false, trigger: 'change' }],
        priorityDirection: [{ type: 'array', required: false, trigger: 'change' }],
        priorityHobbies: [{ type: 'array', required: false, trigger: 'change' }],
        notificationDeadline: [{ 
          required: true, 
          message: '请选择通知截止时间', 
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (this.formData.notificationEnabled && !value) {
              callback(new Error('请选择通知截止时间'));
            } else {
              callback();
            }
          }
        }],
        notificationContent: [{ 
          required: true, 
          message: '请输入通知内容', 
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.formData.notificationEnabled && !value) {
              callback(new Error('请输入通知内容'));
            } else {
              callback();
            }
          }
        }]
      },
      fieldOptions: [],
      directionOptions: [],
      hobbiesOptions: []
    }
  },
  created() {
    this.loading = true;
    this.$nextTick(() => {
      setTimeout(() => {
        this.loading = false;
        this.isInitialized = true;
      }, 100);
    });
  },
  methods: {
    prevStep() {
      if (this.loading) return;
      this.loading = true;
      if (this.activeStep > 0) {
        this.activeStep--;
      }
      this.$nextTick(() => {
        setTimeout(() => {
          this.loading = false;
        }, 50);
      });
    },
    async nextStep() {
      if (this.loading) return;
      // this.loading = true;
      try {
        await this.validateStep(this.activeStep);
        if (this.activeStep < 3) {
          this.activeStep++;
        }
        this.loading = false;
      } catch (error) {
        // 验证失败时不进行任何操作
        this.loading = false;
      }
    },
    validateStep(step) {
      const stepFields = {
        0: ['demandCategory', 'title', 'description'],
        1: ['effectiveDate'],
        2: this.formData.notificationEnabled ? ['notificationDeadline', 'notificationContent'] : ['_blank_'],
        3: []  // 第四步没有必填字段
      };
      
      if (step === 2 && !this.formData.notificationEnabled) {
        return Promise.resolve();
      }
      
      return new Promise((resolve, reject) => {
        this.$refs.mutualForm.validateField(stepFields[step], (error) => {
          if (error) {
            reject(error);
          } else {
            resolve();
          }
        });
      });
    },
    async submitForm() {
      if (this.loading) return;
      try {
        this.loading = true;
        await this.$refs.mutualForm.validate();
        
        // 处理提交数据，将数组转换为逗号分隔的字符串
        const formDataToSubmit = {
          ...this.formData,
          priorityField: Array.isArray(this.formData.priorityField) ? this.formData.priorityField.join(',') : '',
          priorityDirection: Array.isArray(this.formData.priorityDirection) ? this.formData.priorityDirection.join(',') : '',
          priorityHobbies: Array.isArray(this.formData.priorityHobbies) ? this.formData.priorityHobbies.join(',') : ''
        };
        
        const res = await createMutual(formDataToSubmit);
        
        if (res.code === 200) {
          this.$message.success('发布成功');
          this.$router.push('/mutual');
        } else {
          this.$message.error(res.message || '发布失败');
        }
      } catch (error) {
        console.error('发布失败:', error);
        this.$message.error('表单验证失败，请检查填写的内容');
      } finally {
        this.loading = false;
      }
    },
    // 专长领域懒加载
    async handleFieldLazyLoad(node, resolve) {
      const { level } = node;
      try {
        if (level === 0) {
          const res = await getDictValue({
            dictId: "",
            dictName: "个人擅长",
            dictType: "personally_good",
            level: "2"
          });
          resolve(res.code === 200 ? res.data.map(item => ({ ...item, leaf: false })) : []);
        } else if (level === 1) {
          const res = await getDictValue({
            dictId: node.data.dictId,
            dictName: "个人擅长",
            dictType: "personally_good",
            level: "3"
          });
          resolve(res.code === 200 ? res.data : []);
        }
      } catch (error) {
        console.error('加载专长领域失败:', error);
        this.$message.error('加载专长领域失败');
        resolve([]);
      }
    },
    // 工作方向懒加载
    async handleDirectionLazyLoad(node, resolve) {
      const { level } = node;
      try {
        if (level === 0) {
          const res = await getDictValue({
            dictId: "",
            dictName: "行业领域",
            dictType: "industry_field",
            level: "2"
          });
          resolve(res.code === 200 ? res.data.map(item => ({ ...item, leaf: false })) : []);
        } else if (level === 1) {
          const res = await getDictValue({
            dictId: node.data.dictId,
            dictName: "行业领域",
            dictType: "industry_field",
            level: "3"
          });
          resolve(res.code === 200 ? res.data : []);
        }
      } catch (error) {
        console.error('加载工作方向失败:', error);
        this.$message.error('加载工作方向失败');
        resolve([]);
      }
    },
    // 兴趣爱好懒加载
    async handleHobbiesLazyLoad(node, resolve) {
      const { level } = node;
      try {
        if (level === 0) {
          const res = await getDictValue({
            dictId: "",
            dictName: "兴趣爱好",
            dictType: "self_hobbies",
            level: "2"
          });
          resolve(res.code === 200 ? res.data.map(item => ({ ...item, leaf: false })) : []);
        } else if (level === 1) {
          const res = await getDictValue({
            dictId: node.data.dictId,
            dictName: "兴趣爱好",
            dictType: "self_hobbies",
            level: "3"
          });
          resolve(res.code === 200 ? res.data : []);
        }
      } catch (error) {
        console.error('加载兴趣爱好失败:', error);
        this.$message.error('加载兴趣爱好失败');
        resolve([]);
      }
    },
    handleFieldChange(value) {
      console.log('选中的专长领域:', value);
    },
    handleDirectionChange(value) {
      console.log('选中的工作方向:', value);
    },
    handleHobbiesChange(value) {
      console.log('选中的兴趣爱好:', value);
    }
  }
}
</script>

<style lang="less" scoped>
.create-mutual {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;

  .form-card {
    max-width: 800px;
    margin: 0 auto;
    min-height: 500px;
    position: relative;
    
    .page-title {
      font-size: 20px;
      color: #303133;
      margin-bottom: 25px;
      display: flex;
      align-items: center;
      gap: 8px;
      
      i {
        font-size: 24px;
        color: #409EFF;
      }
    }
    
    .step-header {
      position: sticky;
      top: 0;
      background: #fff;
      z-index: 1;
      padding: 20px 0;
      border-bottom: 1px solid #ebeef5;
      margin-bottom: 20px;
    }
  }
  
  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
    
    i {
      font-size: 18px;
      color: #409EFF;
    }
    
    span {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }
  
  .form-section {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
  }
  
  .switch-tip {
    margin-left: 10px;
    color: #909399;
    font-size: 13px;
  }
  
  .step-content {
    position: absolute;
    left: 0;
    right: 0;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
    padding: 20px;
    
    &.is-active {
      position: relative;
      opacity: 1;
      visibility: visible;
    }
  }
  
  .el-form-item {
    margin-bottom: 22px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .el-form {
    min-height: 400px;
    position: relative;
  }
  
  .step-actions {
    position: sticky;
    bottom: 0;
    background: #fff;
    padding: 20px 0;
    margin-top: 20px;
    text-align: center;
    
    .el-button {
      min-width: 100px;
      transition: all 0.3s ease;
      
      &[disabled] {
        cursor: not-allowed;
      }
    }
  }
}

:deep(.el-select-dropdown__item) {
  i {
    margin-right: 8px;
    color: #909399;
  }
}

@media screen and (max-width: 768px) {
  .create-mutual {
    .form-card {
      margin: 0;
      border-radius: 0;
    }
    
    .step-content {
      padding: 15px;
    }
    
    .step-actions {
      padding: 15px 0;
      
      .el-button {
        min-width: 80px;
      }
    }
  }
}

/deep/ .el-cascader {
  width: 100%;
  
  .el-input__inner {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding-left: 15px;
    font-size: 14px;
    
    &::placeholder {
      color: #999;
    }
  }
}

.custom-steps {
  :deep(.el-step) {
    .el-step__head {
      .el-step__icon {
        width: 40px;
        height: 40px;
        font-size: 20px;
        background: #f5f7fa;
        border-color: #dcdfe6;
        
        i {
          font-size: 20px;
          color: #909399;
        }
      }
      
      &.is-process {
        .el-step__icon {
          background: #409EFF;
          border-color: #409EFF;
          
          i {
            color: #fff;
          }
        }
      }
      
      &.is-success {
        .el-step__icon {
          background: #67C23A;
          border-color: #67C23A;
          
          i {
            color: #fff;
          }
        }
      }
    }
    
    .el-step__main {
      .el-step__title {
        font-size: 15px;
        font-weight: 500;
        
        &.is-process {
          color: #409EFF;
          font-weight: 600;
        }
        
        &.is-success {
          color: #67C23A;
        }
      }
      
      .el-step__description {
        font-size: 13px;
        color: #909399;
      }
    }
    
    .el-step__line {
      background-color: #dcdfe6;
      
      &.is-process {
        background-color: #409EFF;
      }
      
      &.is-success {
        background-color: #67C23A;
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .custom-steps {
    :deep(.el-step) {
      .el-step__head {
        .el-step__icon {
          width: 32px;
          height: 32px;
          font-size: 16px;
          
          i {
            font-size: 16px;
          }
        }
      }
      
      .el-step__main {
        .el-step__title {
          font-size: 13px;
        }
        
        .el-step__description {
          font-size: 12px;
        }
      }
    }
  }
}
</style>